import { useEventListener } from '@vueuse/core';
import gsap from 'gsap';
import { ref } from 'vue';

export default function usePins() {
  useEventListener(window, 'popstate', () => {
    isPinsVisible.value = false;
  });

  const onToPinsClick = (item: {
    id: string;
    location: { translateX: number; translateY: number };
  }) => {
    history.pushState(null, '', `/pins/${item.id}`);

    isPinsVisible.value = true;
    currentPins.value = item;
  };

  const isPinsVisible = ref<boolean>(false);
  const currentPins = ref<Record<string, any>>({});

  const pinsTransitionEvents = {
    beforeEnter: (el: Element) => {
      gsap.set(el, {
        scaleX: 0,
        scaleY: 0,
        transformOrigin: '0,0',
        translateX: currentPins.value.location?.translateX,
        translateY: currentPins.value.location?.translateY,
        opacity: 0
      });
    },
    enter: (el: Element, done: () => void) => {
      gsap.to(el, {
        scaleX: 1,
        scaleY: 1,
        opacity: 1,
        duration: 0.3,
        translateX: 0,
        translateY: 0,
        onComplete: done
      });
    },

    leave: (el: Element, done: () => void) => {
      gsap.to(el, {
        scaleX: 0,
        scaleY: 0,
        opacity: 0,
        duration: 0.3,
        translateX: currentPins.value.location?.translateX,
        translateY: currentPins.value.location?.translateY,
        onComplete: done
      });
    }
  };

  return {
    onToPinsClick,
    isPinsVisible,
    currentPins,
    pinsTransitionEvents
  };
}
